package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.agent.builder.AgentBuilder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

//    java.sql.SQLIntegrityConstraintViolationException:
//    键值对已存在
//    Duplicate entry 'lily' for key 'employee.idx_username'
//重载异常处理方法：加一个捕获sql异常的方法

    /**
     *
     * @param ex
     * @return
     */
    @ExceptionHandler  //用户名已存在
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //获得异常信息
        String message = ex.getMessage();
        //若异常信息是此错误
        if(message.contains("Duplicate entry")){
        //    Duplicate entry 'lily' for key 'employee.idx_username' 动态的把 lily提取出来
        //数组对象
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXIST;
        //前端提示错误信息
            return Result.error(msg);
        }else{
        //未知错误
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

    }
}
